<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { Message, Message as ElMessage } from 'element-ui'
import {
  exportCommunityExcel,
  exportCommunitySpecialShp,
  exportFileByType,
  exportNewBuildExcel,
  exportRegionBaseShp,
  exportRegionExcel,
  exportRegionSpecialShp,
  exportShpByType,
  getExportExcelData,
} from '@api/export'
import { downloadBlobFile, downloadFileWithBlob } from '@u/download/index'
import {
  getColumns,
  getExcelData,
  getExcelDataOld,
  getSpecialExcelData,
  getSpecialQuestion,
  sheet2blob,
} from '@u/download/getDownloadInfo'
import { utils } from 'xlsx'
import { queryArea } from '@/api/question'
import axios from 'axios'

const user = JSON.parse(localStorage.getItem('user')).user

const specialRegionId = [
  '500103000000',
  '500104000000',
  '500105000000',
  '500106000000',
  '500107000000',
  '500108000000',
  '500109000000',
  '500112000000',
  '500113000000',
  '500191000000',
  '500193000000',
]

const isMainRegion = computed(() => {
  return user.roleLevel === 2 && specialRegionId.includes(user.refId)
})

const tableData = ref([
  {
    id: 'residence',
    name: '小区数据',
  },
  {
    id: 'community',
    name: '社区数据',
  },
  {
    id: 'street',
    name: '街道数据',
    canDownloadFile: false,
  },
  {
    id: 'satisfaction',
    name: '满意度调查数据',
    mainHidden: true,
  },
  {
    id: 'proposal',
    name: '城市建议数据',
  },
  {
    id: 'region',
    name: '专项调查数据',
    canDownloadFile: false,
  },
  // {
  //   id: 'region',
  //   name: '市级数据',
  //   canDownloadShp: false,
  // },
])

defineProps({
  visible: Boolean,
})

const areaInfoVal = ref([])

const getTableData = () => {
  const level = user.roleLevel
  switch (level) {
    case 0:
    case 4:
      tableData.value.push({
        id: 'building',
        name: '楼宇数据',
        canDownloadShp: false,
        canDownloadFile: false,
      })
      break
    case 2:
      break
    case 1:
      tableData.value = tableData.value.filter((item) => item.id !== 'region')
      break
    case 3:
      tableData.value = tableData.value.filter(
        (item) => item.id !== 'region' && item.id !== 'street'
      )
      break
  }
}

const getUserId = () => {
  const level = user.roleLevel
  const id = user.refId
  let result = {}
  switch (level) {
    case 0:
    case 4:
      result = {
        cityId: id,
      }
      break
    case 2:
      result = {
        regionId: id,
      }
      break
    case 1:
      result = {
        streetId: id,
      }
      break
    case 3:
      result = {
        communityId: id,
      }
      break
  }
  return result
}

const getFirstColumn = (id) => {
  let text = ''
  switch (id) {
    case 'region':
      text = '区县名称'
      break
    case 'street':
      text = '街道名称'
      break
    case 'community':
      text = '社区id'
      break
    case 'residence':
      text = '社区名称'
      break
    case 'satisfaction':
      text = '手机号码'
      break
  }
  return text
}

const handleDownloadClick = (row, type) => {
  const key = type + '_' + row.id
  loadingStatus.value[key] = true
  const { id, name } = row
  if (type === 'excel') {
    if (id === 'building') {
      exportNewBuildExcel({
        ...getUserId(),
      })
        .then((res) => {
          downloadFileWithBlob(res, name + '_excel.csv')
        })
        .catch((err) => {
          ElMessage.error('下载失败')
        })
        .finally(() => {
          loadingStatus.value[key] = false
        })
      return
    }
    if (
      id === 'community' ||
      id === 'proposal' ||
      id === 'satisfaction' ||
      id === 'residence' ||
      id === 'build' ||
      id === 'street'
    ) {
      let params = {
        type: id,
        ...getUserId(),
      }
      if (id === 'satisfaction' || id === 'proposal') {
        params = {
          type: id,
        }
      }
      exportCommunityExcel(params, id)
        .then((res) => {
          downloadFileWithBlob(res, name + '_shp.zip')
        })
        .catch((err) => {
          ElMessage.error('下载失败')
        })
        .finally(() => {
          loadingStatus.value[key] = false
        })
      return
    }
    //
    let params = {
      type: id,
      ...getUserId(),
    }
    if (id === 'satisfaction' || id === 'proposal') {
      params = {
        type: 'satisfaction',
      }
    }
    getExportExcelData(params)
      .then((res) => {
        // console.log(res)
        if (res.success) {
          if (!res.data) {
            Message.error('暂无数据！')
            return
          }
          // console.log(res.data)
          const { templateInfos, resultMap } = res.data

          if (id === 'street') {
            const data = templateInfos[0]?.children || []
            const specialList = []
            const list = []
            data[0]?.children?.forEach((item) => {
              if (item.pkid === '410') {
                specialList.push(item)
              } else {
                list.push(item)
              }
            })
            const questions = getColumns(list)
            const result = []
            const header = ['区县名称', '街道名称']
            questions.forEach((question) => {
              header.push(question.question)
            })
            result.push(header)
            const areaInfo = areaInfoVal.value
            getExcelData(questions, resultMap, result, areaInfo, 'street')
            const worksheet = utils.aoa_to_sheet(result)
            const specialQuestions = getSpecialQuestion(specialList)
            const specialResult = getSpecialExcelData(
              specialQuestions,
              resultMap,
              areaInfo,
              ['区县名称', '街道名称'],
              'street'
            )
            const blob = sheet2blob([
              {
                sheet: worksheet,
              },
              ...specialResult,
            ])
            downloadBlobFile(
              {
                data: blob,
              },
              name + '_excel.xlsx'
            )
            return
          }

          const questions = getColumns(templateInfos)
          // console.log(questions)
          const result = []
          const header = [getFirstColumn(id)]
          questions.forEach((question) => {
            header.push(question.question)
          })
          result.push(header)
          const areaInfo = areaInfoVal.value
          // if (id === 'satisfaction') {
          getExcelData(questions, resultMap, result, areaInfo)
          // } else {
          //   getExcelData(questions, resultMap, result, areaInfo)
          // }
          const worksheet = utils.aoa_to_sheet(result)
          const blob = sheet2blob([
            {
              sheet: worksheet,
            },
          ])
          downloadBlobFile(
            {
              data: blob,
            },
            name + '_excel.xlsx'
          )
        }
      })
      .catch((err) => {
        // console.log(err)
        ElMessage.error('下载失败')
      })
      .finally(() => {
        loadingStatus.value[key] = false
      })
  } else if (type === 'shp') {
    //根据类型下载shp
    exportShpByType(id)
      .then((res) => {
        // console.log(res)
        downloadFileWithBlob(res, name + '_shp.zip')
      })
      .catch((err) => {
        ElMessage.error('下载失败')
      })
      .finally(() => {
        loadingStatus.value[key] = false
      })
  } else {
    exportFileByType(id)
      .then((res) => {
        // console.log(res)
        downloadFileWithBlob(res, name + '_file.zip')
      })
      .catch((err) => {
        ElMessage.error('下载失败')
      })
      .finally(() => {
        loadingStatus.value[key] = false
      })
  }
}

const getAreaInfo = async () => {
  const res = await queryArea({})
  if (res.success) {
    areaInfoVal.value = res.data
  } else {
    Message.error(res.message)
  }
}

onMounted(async () => {
  getTableData()
  // await getAreaInfo()
})

const emit = defineEmits(['close'])

const handleClose = () => {
  emit('close')
}

const loadingStatus = ref({
  excel_build: false,
  excel_residence: false,
  shp_residence: false,
  file_residence: false,
  excel_community: false,
  shp_community: false,
  file_community: false,
  excel_street: false,
  shp_street: false,
  file_street: false,
  excel_satisfaction: false,
  shp_satisfaction: false,
  file_satisfaction: false,
  excel_proposal: false,
  excel_proposal_main: false,
  shp_proposal: false,
  file_proposal: false,
  excel_region: false,
  shp_region: false,
  file_region: false,
  excel_region_live: false,
  excel_region_community: false,
  excel_region_culture: false,
  excel_region_build: false,
  excel_region_business: false,
  excel_region_industry: false,
  excel_region_shop: false,
  excel_region_other: false,
  excel_region_vacant: false,
  shp_region_live: false,
  shp_vacant_space: false,
  shp_community_live: false,
  excel_building: false,
})

const handleDownloadMain = (row, type) => {
  const key = type + '_' + row.id
  const { id } = row
  if (id === 'satisfaction') {
    loadingStatus.value[key] = true
    axios
      .get('question.xlsx', {
        responseType: 'blob',
      })
      .then((res) => {
        downloadFileWithBlob(res, '满意度_中心城区居民问卷.xlsx')
      })
      .catch((err) => {
        ElMessage.error('下载失败')
      })
      .finally(() => {
        loadingStatus.value[key] = false
      })
  } else {
    loadingStatus.value.excel_proposal_main = true
    axios
      .get('suggest.xlsx', {
        responseType: 'blob',
      })
      .then((res) => {
        downloadFileWithBlob(res, '满意度_中心城区改善建议.xlsx')
      })
      .catch((err) => {
        ElMessage.error('下载失败')
      })
      .finally(() => {
        loadingStatus.value.excel_proposal_main = false
      })
  }
}

const regionInfos = [
  {
    id: 'region-live',
    name: '居住区',
  },
  {
    id: 'region-community',
    name: '居住区（社区填报）',
  },
  {
    id: 'region-culture',
    name: '历史文化片区',
  },
  {
    id: 'region-build',
    name: '历史建筑',
  },
  {
    id: 'region-business',
    name: '旧商业商务区',
  },
  {
    id: 'region-industry',
    name: '老旧工业仓储区',
  },
  {
    id: 'region-shop',
    name: '老旧商贸市场',
  },
  {
    id: 'region-other',
    name: '其他需要更新片区',
  },
  {
    id: 'region-vacant',
    name: '空置闲置地',
  },
]

const handleRegionDownload = (item) => {
  const loadingKey = 'excel_' + item.id.replace('-', '_')
  loadingStatus.value[loadingKey] = true
  exportRegionExcel({
    type: item.id,
  })
    .then((res) => {
      downloadFileWithBlob(res, item.name + '_excel.xlsx')
    })
    .catch((err) => {
      ElMessage.error('下载失败')
    })
    .finally(() => {
      loadingStatus.value[loadingKey] = false
    })
}

const handleRegionShpDownload = (name, type) => {
  let promise
  switch (type) {
    case 'region-live':
      promise = exportRegionBaseShp({})
      break
    case 'vacant-space':
      promise = exportRegionSpecialShp({})
      break
    case 'community-live':
      promise = exportCommunitySpecialShp({})
      break
  }
  const loadingKey = 'shp_' + type.replace('-', '_')
  loadingStatus.value[loadingKey] = true
  promise
    .then((res) => {
      downloadFileWithBlob(res, name + '_shp.zip')
    })
    .catch((err) => {
      ElMessage.error('下载失败')
    })
    .finally(() => {
      loadingStatus.value[loadingKey] = false
    })
}
</script>

<template>
  <el-dialog
    :visible="visible"
    class="detail-table-dialog"
    title="数据下载"
    width="45%"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="name" label="" align="center"> </el-table-column>
      <el-table-column align="center" label="">
        <template #default="scope">
          <template
            v-if="
              scope.row.id !== 'residence' &&
              scope.row.id !== 'proposal' &&
              scope.row.id !== 'region'
            "
          >
            <el-button
              v-if="isMainRegion && scope.row.mainHidden"
              :loading="loadingStatus['excel_' + scope.row.id]"
              type="text"
              @click="handleDownloadMain(scope.row, 'excel')"
            >
              <span>中心城区excel下载</span>
            </el-button>
            <el-button
              v-else
              :loading="loadingStatus['excel_' + scope.row.id]"
              type="text"
              @click="handleDownloadClick(scope.row, 'excel')"
            >
              <span>excel下载</span>
            </el-button>
          </template>
          <template v-else-if="scope.row.id === 'region'">
            <el-button
              v-for="(item, index) in regionInfos"
              :key="index"
              type="text"
              :loading="loadingStatus['excel_' + item.id.replace('-', '_')]"
              @click="handleRegionDownload(item)"
              >{{ item.name }}</el-button
            >
          </template>
          <template v-else-if="scope.row.id === 'proposal'">
            <el-button
              :loading="loadingStatus['excel_' + scope.row.id]"
              type="text"
              @click="handleDownloadClick(scope.row, 'excel')"
            >
              <span>excel下载</span>
            </el-button>
            <el-button
              v-if="isMainRegion"
              :loading="loadingStatus.excel_proposal_main"
              type="text"
              @click="
                handleDownloadMain(
                  {
                    id: 'proposal',
                  },
                  'excel'
                )
              "
            >
              <span>中心城区excel下载</span>
            </el-button>
          </template>
          <template v-else>
            <el-button
              :loading="loadingStatus['excel_' + scope.row.id]"
              type="text"
              @click="handleDownloadClick(scope.row, 'excel')"
            >
              <span>小区excel下载</span>
            </el-button>
            <el-button
              :loading="loadingStatus['excel_' + 'build']"
              type="text"
              @click="
                handleDownloadClick(
                  {
                    name: '楼宇数据',
                    id: 'build',
                  },
                  'excel'
                )
              "
            >
              <span>楼宇excel下载</span>
            </el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="">
        <template #default="scope">
          <template v-if="scope.row.id !== 'region'">
            <span
              v-if="
                scope.row.canDownloadShp === false ||
                (isMainRegion && scope.row.mainHidden)
              "
              >/</span
            >
            <el-button
              :loading="loadingStatus['shp_' + scope.row.id]"
              type="text"
              v-else
              @click="handleDownloadClick(scope.row, 'shp')"
            >
              <span>shp下载</span>
            </el-button>
          </template>
          <template v-else>
            <el-button
              type="text"
              :loading="loadingStatus.shp_region_live"
              @click="handleRegionShpDownload('片区范围', 'region-live')"
            >
              片区范围shp下载
            </el-button>
            <el-button
              type="text"
              :loading="loadingStatus.shp_vacant_space"
              @click="handleRegionShpDownload('闲置空间', 'vacant-space')"
              >其他空间范围shp下载</el-button
            >
            <el-button
              type="text"
              :loading="loadingStatus.shp_community_live"
              @click="handleRegionShpDownload('社区居住区', 'community-live')"
              >社区居住区shp下载</el-button
            >
          </template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="" v-if="user.roleLevel === 2">
        <template #default="scope">
          <span
            v-if="
              scope.row.canDownloadFile === false ||
              (isMainRegion && scope.row.mainHidden)
            "
            >/</span
          >
          <el-button
            :loading="loadingStatus['file_' + scope.row.id]"
            type="text"
            v-else
            @click="handleDownloadClick(scope.row, 'file')"
          >
            <span>多媒体文件下载</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--    <div class="download-all">-->
    <!--      <el-button icon="el-icon-download" type="text">下载全部</el-button>-->
    <!--    </div>-->
  </el-dialog>
</template>

<style lang="scss">
.detail-table-dialog {
  .query-content {
    margin-bottom: 15px;

    .community-data-download-button {
      margin-left: 12px;
      height: 40px;
    }
  }

  .el-table__header-wrapper {
    display: none;
  }

  .download-all {
    display: flex;
    justify-content: flex-end;

    .el-button {
      padding-top: 20px;
      padding-bottom: 0;
    }
  }

  .el-dialog__body {
    padding-top: 15px;
  }
}
</style>
